import axios from "axios";
import { getToken, setToken } from '@/utils/token-util';
import { API_BASE_PREFIX, TOKEN_HEADER_NAME } from '@/config/setting';
/**
 * 用于流式调用大模型接口的客户端，支持中止（AbortController）
 */
export default class LLMStreamClient {
  /**
   * 构造函数
   * @param {string} baseURL - 接口基础地址
   * @param {object} defaultHeaders - 默认请求头
   */
  constructor(baseURL, defaultHeaders = {}) {
    this.axiosInstance = axios.create({
      baseURL: API_BASE_PREFIX,
      headers: {
        ...defaultHeaders,
        "Content-Type": "application/json",
        "Authorization": `Bearer ${getToken()}`, // 添加 Bearer Token
      },
      adapter: "fetch",
    });
    debugger;
    this._abortController = null;
  }

  /**
   * 流式调用大模型接口
   * @param {object} options
   * @param {string} options.path - API 路径
   * @param {object} options.data - 请求体
   * @param {function} options.onMessage - 每收到一条消息时回调
   * @param {function} options.onEnd - 结束时回调
   * @param {function} options.onError - 出错时回调
   */
  async streamChat({ path, data, onMessage, onEnd, onError }) {
    this._abortController = new AbortController();

    (async () => {
      try {
        const response = await this.axiosInstance.post(
          path,
          data,
          {
            responseType: "stream",
            signal: this._abortController.signal,
          }
        );

        const stream = response.data;
        const reader = stream.getReader();
        const decoder = new TextDecoder("utf-8");

        let done = false;
        let buffer = "";
        while (!done) {
          const { value, done: streamDone } = await reader.read();
          done = streamDone;
          if (value) {
            buffer += decoder.decode(value, { stream: true });
            let lines = buffer.split("\n");
            buffer = lines.pop();

            for (const line of lines) {
              if (!line.trim()) continue;
              if (line.startsWith("data:")) {
                const dataStr = line.replace(/^data:\s*/, "");
                if (dataStr === "[DONE]") {
                  onEnd && onEnd();
                  return;
                }
                onMessage && onMessage(dataStr);
              } else {
                onMessage && onMessage(line);
              }
            }
          }
        }
        onEnd && onEnd();
      } catch (err) {
        if (err.name === "CanceledError" || err.name === "AbortError") {
          onEnd && onEnd();
        } else {
          onError && onError(err);
        }
      }
    })();
  }

  /**
   * 主动停止（中止）流式请求
   */
  stop() {
    if (this._abortController) {
      this._abortController.abort();
      this._abortController = null;
    }
  }
}